"""1、读取文本文件test1.txt（英文）进行词语统计。讲统计结果降序排序后（序号、
词语、频率）存放到test1.csv 。"""
import pandas as pd
from collections import Counter

# Read the text file
with open('1/test1.txt', 'r') as f:# 即使发生异常也会确保文件关闭
    words = f.read().lower().split()

# Count word frequencies
word_counts = Counter(words)

# Sort by frequency (descending)
sorted_words = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)
df=pd.DataFrame(sorted_words,columns=["word","frequency"])
df.to_csv("test1.csv")

# Write to CSV
# with open('test1.csv', 'w', newline='') as f:
#     writer = csv.writer(f)
#     writer.writerow(['序号', '词语', '频率'])  # Header
#     for i, (word, count) in enumerate(sorted_words, 1):
#         writer.writerow([i, word, count])